import { DataSource, DataSourceOptions } from 'typeorm'
// import * as path from 'path'
//
import * as dotenv from 'dotenv'
import * as fs from 'fs'
import * as process from 'process'
import * as path from 'path'
import { TypeOrmModuleOptions } from '@nestjs/typeorm'

// 根据环境变量读取不同的.env文件
function getEnvFile(env: string) {
  if (fs.existsSync(env)) {
    return dotenv.parse(fs.readFileSync(env))
  }
  return {}
}

function buildConnection() {
  const defaultConfig = getEnvFile('.env')
  const env = process.env.NODE_ENV || 'development'
  const envConfig = getEnvFile(`./env/${env}.env`)
  const config = { ...defaultConfig, ...envConfig }
  return {
    type: 'mysql',
    host: config.DB_HOST,
    port: +config.DB_PORT,
    username: config.DB_USERNAME,
    password: config.DB_PWD,
    database: config.DB_DATABASE,
    entities: [path.join(__dirname, '**/*.entity{.ts,.js}')],
    synchronize: true,
    migrations: [],
    subscribers: []
  } as TypeOrmModuleOptions
}
export const OrmConfig = buildConnection()
export const AppDataSource = new DataSource(OrmConfig as DataSourceOptions)
